package com.zhj.bz.algorithm.sort.insert;

import com.zhj.tool.CallBack;
import com.zhj.tool.TimeTools;

import java.util.Arrays;

/**
 * @author zhj
 */
public class InsertSort {

    public static void main(String[] args) {
        int[] arr = {-6, 9, 21, 10, -1};
        sort(arr);
        System.out.println(Arrays.toString(arr));

        int[] bigArr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            bigArr[i] = (int) (Math.random() * 80000);
        }
        System.out.println("选择排序：");
        TimeTools.useTime(new CallBack(){
            //定义execute方法
            public void execute(){
                sort(bigArr);
            }
        });
    }

    public static void sort(int[] arr) {

        int insertValue = 0;
        int insertIndex = 0;
        for (int i = 1; i < arr.length; i++) {
            insertValue = arr[i];
            insertIndex = i-1;
            // 保证插入位置不越界，找到位置循环暂停
            while (insertIndex >= 0 && insertValue < arr[insertIndex]) {
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex -= 1;
            }
            if (insertIndex + 1 != i) {
                arr[insertIndex + 1] = insertValue;
            }
        }
    }
}
